//
//  IAPManager.m
//  KKSDK
//
//  Created by jay Win on 2019/5/15.
//  Copyright © 2019 jay Win. All rights reserved.
//

#import "IAPManager.h"
#import <RMStore.h>
#import "RMAppReceipt.h"
#import <Adjust.h>
#import <Analytics.h>
#import <AdSupport/AdSupport.h>

@interface IAPManager()<SKPaymentTransactionObserver>{
    
}
- (void)setupTransactionObservers;

@end
@implementation IAPManager
+ (instancetype)shareManager {
    static IAPManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [IAPManager new];
    });
    return manager;
}
- (instancetype)init
{
    NSLog(@"初始化IAP");
    self = [super init];
    if (self) {
        [self setupTransactionObservers];
    }
    return self;
}
- (void)restore{
    [[RMStore defaultStore] restoreTransactionsOnSuccess:^(NSArray *transactions) {
        NSLog(@"进入恢复购买");
    } failure:^(NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
        
    
        });
    }];
}
- (void)queryProductInfo{
    [[RMStore defaultStore]requestProducts: [NSSet setWithObjects:
                                             @"com.playmil.starblast.games.gem00",
                                             @"com.playmil.starblast.games.gem01",
                                             @"com.playmil.starblast.games.gem02",
                                             @"com.playmil.starblast.games.gem03",
                                             @"com.playmil.starblast.games.gem04",
                                             @"com.playmil.starblast.games.gem05",
                                             @"com.playmil.starblast.games.one_time_purchase",
                                             @"com.playmil.starblast.games.weekly",
                                             @"com.playmil.starblast.games.month",
                                             @"com.playmil.starblast.games.year",
                                             nil] success:^(NSArray *products, NSArray *invalidProductIdentifiers) {
        
        
        NSString *currencySymbol=@"$";
        
        //获取临时货币单元符
        __block SKProduct *tempProduction = [[RMStore defaultStore] productForIdentifier:@"com.playmil.starblast.games.gem00"];
        //
        NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc]init];
        numberFormatter.usesSignificantDigits = true;
        numberFormatter.maximumSignificantDigits = 100;
        numberFormatter.groupingSeparator = @"";
        numberFormatter.numberStyle = NSNumberFormatterDecimalStyle;
        numberFormatter.locale = tempProduction.priceLocale;
        
        
        
        NSMutableArray *jsonArray = [NSMutableArray array];
    
        
        for (SKProduct *product in products) {
            NSMutableDictionary *obj = [NSMutableDictionary dictionary];
            obj[@"pid"]=product.productIdentifier;
           
            if (@available(iOS 10.0, *)) {
                currencySymbol = tempProduction.priceLocale.currencySymbol;
            }else{
                currencySymbol = numberFormatter.internationalCurrencySymbol;
            }
            
            obj[@"price"]=[currencySymbol stringByAppendingString:[numberFormatter stringFromNumber:product.price]];
            obj[@"pricec"]=[product.priceLocale localeIdentifier];
            [jsonArray addObject:obj];
         
           
        }
        NSDictionary *dic = @{@"iosQueryResult":jsonArray};
        NSLog(@"json:%@",[self dictToJSONString:dic]);
       
    } failure:^(NSError *error) {
        NSLog(@"查询所有商品失败:%@",[error localizedDescription]);
    }];
}
- (NSString *)dictToJSONString:(NSDictionary *)dic {
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}





- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions{
      for (SKPaymentTransaction *transaction in transactions){
          switch (transaction.transactionState) {
              case SKPaymentTransactionStatePurchased:
                  NSLog(@"购买成功");
                  
                  break;
                  
              case SKPaymentTransactionStateFailed:
                  NSLog(@"购买失败");
                
                  break;
              case SKPaymentTransactionStateRestored:
                  NSLog(@"恢复购买");
                  if ([transaction.payment.productIdentifier isEqualToString:@"com.playmil.starblast.games.one_time_purchase"]) {
             
                  }
                  break;
              case SKPaymentTransactionStateDeferred:
                  break;
              default:
                  break;
          }
      }
}
- (BOOL)paymentQueue:(SKPaymentQueue *)queue shouldAddStorePayment:(SKPayment *)payment forProduct:(SKProduct *)product{
    return  YES;
}

- (void)setupTransactionObservers{
     [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
}
- (BOOL)hasSubscribed{
     RMAppReceipt *receipt = [RMAppReceipt bundleReceipt];
    for (RMAppReceiptIAP *iap in receipt.inAppPurchases) {
        if ([iap.productIdentifier isEqualToString: @"com.playmil.starblast.games.weekly"]
            || [iap.productIdentifier isEqualToString:@"com.playmil.starblast.games.month"]
            || [iap.productIdentifier isEqualToString:@"com.playmil.starblast.games.year"]) {
            return YES;
        }
    }
    return NO;
}
- (void)refreshSubscriptionState{
    BOOL isSubscription = NO;
    NSDate *currentDate = [NSDate date];
    RMAppReceipt *receipt = [RMAppReceipt bundleReceipt];
    
    for (RMAppReceiptIAP *iap in receipt.inAppPurchases) {
        if ([iap.productIdentifier isEqualToString:@"com.playmil.starblast.games.weekly"]
            || [iap.productIdentifier isEqualToString:@"com.playmil.starblast.games.month"]
            || [iap.productIdentifier isEqualToString:@"com.playmil.starblast.games.year"]) {
            if ([iap isActiveAutoRenewableSubscriptionForDate:currentDate]) {
                isSubscription = YES;
                break;
            }
        }
    }
    //todo 发送是否为订阅信息
    BOOL isRemoveIap = NO;
    for (RMAppReceiptIAP *iap in receipt.inAppPurchases) {
        if ([iap.productIdentifier isEqualToString:@"com.playmil.starblast.games.one_time_purchase"]) {
            isRemoveIap = YES;
            break;
        }
    }
}
- (BOOL)hasRemoveAds{
    BOOL isRemoveIap = NO;
     RMAppReceipt *receipt = [RMAppReceipt bundleReceipt];
    for (RMAppReceiptIAP *iap in receipt.inAppPurchases) {
        if ([iap.productIdentifier isEqualToString:@"com.playmil.starblast.games.one_time_purchase"]) {
            isRemoveIap = YES;
            break;
        }
    }
    return isRemoveIap;
}

- (void)dealloc {
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}
- (void)validateReceiptViaServer{
    NSString *isForProduction = @"false";
#if DEBUG
    isForProduction = @"false";
#else
    isForProduction = @"true";
#endif
     NSString *urlString = [NSString stringWithFormat:RECEIPT_VALIDATION_URL_FORMAT, [[NSBundle mainBundle] bundleIdentifier], isForProduction];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];
    NSData *receiptData = [NSData dataWithContentsOfURL:[[NSBundle mainBundle]appStoreReceiptURL]];
    if (!receiptData) {
        return;
    }
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSString *receiptString = [receiptData base64EncodedStringWithOptions:0];
    if (receiptString) {
        [params setObject:receiptString forKey:@"receipt-data"];
    }
    NSString *deviceId = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    if (deviceId) {
        [params setObject:deviceId forKey:@"deviceid"];
    }
    NSString * conunty = [[NSLocale currentLocale] objectForKey:NSLocaleCountryCode];
    if (conunty) {
        [params setObject:conunty forKey:@"conunty"];
    }
    NSString * trackerName = [Adjust attribution].trackerName;
    if (trackerName) {
        [params setObject:trackerName forKey:@"trackerName"];
    }
    NSString * campaign =[Adjust attribution].campaign;
    if (campaign) {
        [params setObject:campaign forKey:@"campaign"];
    }
    NSString * idfa = [ASIdentifierManager sharedManager].advertisingIdentifier.UUIDString;
    if (idfa) {
        [params setObject:idfa forKey:@"idfa"];
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:nil];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[jsonData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:jsonData];
    
    [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (!error) {
            
        }else {
            
        }
    }]resume];
}
- (void)purchaseItem:(NSString *)productionID{
    [[RMStore defaultStore] addPayment:productionID success:^(SKPaymentTransaction *transaction) {
        [[IAPManager shareManager] validateReceiptViaServer];
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"进行购买%@",productionID);
        });
    } failure:^(SKPaymentTransaction *transaction, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"购买商品id失败");
        });
    }];
}



@end
